package com.ruoyi.api.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.api.ApiResult;
import com.ruoyi.common.core.domain.api.CodeMsg;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.localAssert.LocalAssert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.json.JsonUtils;
import com.ruoyi.common.utils.kuaidiniao.*;
import com.ruoyi.common.utils.rest.RestTemplateUtil;
import com.ruoyi.common.utils.weCat.WeCatUtils;
import com.ruoyi.common.utils.weCat.template.ShipTemplate;
import com.ruoyi.pos.api.dto.user.UserTeamDto;
import com.ruoyi.pos.api.vo.user.UserTeamListVo;
import com.ruoyi.pos.web.domain.TGradeInfo;
import com.ruoyi.pos.web.mapper.TGradeInfoMapper;
import com.ruoyi.pos.web.mapper.TUserTeamInfoMapper;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author luobo
 * @title: TestController
 * @projectName pos
 * @description: TODO
 * @date 2021-11-30 10:27:07
 */
@RestController("testRestTemplateCtroller")
@RequestMapping("/api/common")
public class TestController {
    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    WeCatUtils weCatUtils;
    @Autowired
    KdApiUtil kdApiUtil;
    @Autowired
    private TGradeInfoMapper gradeInfoMapper;
    @Autowired
    private TUserTeamInfoMapper userTeamInfoMapper;

    @PostMapping("/testApi")
    @ResponseBody
    public ApiResult<T> testApi(@RequestBody @Validated TestBean bean, BindingResult result) {
        System.out.println(result.hasErrors() + "----" + result.getFieldError());
        return ApiResult.success(CodeMsg.SUCCESS, "");
    }

    @PostMapping("/testApi2")
    @ResponseBody
    public ApiResult<T> testApi2(@Validated @RequestBody TestBean bean) {
        //System.out.println(result.hasErrors() + "----" + result.getFieldError());
        return ApiResult.success(CodeMsg.SUCCESS, "");
    }

    @PostMapping("/testAssert")
    @ResponseBody
    public ApiResult<T> testApi1(@RequestBody @Validated TestBean bean) {
        LocalAssert.hasNotText(bean.getName(), "姓名不能为空了啊");
        if (StringUtils.isEmpty(bean.getName())) {
            throw new ServiceException("姓名不能为空了啊");
        }
        return ApiResult.success(CodeMsg.SUCCESS, "");
    }

    @RequestMapping(value = "/testLocal", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testLocal(String userId, String appSecret, String touser, String template_id) throws IOException {
        try {
            // 组装应用级参数
            System.out.println("--------testLocal--------");
            List<TGradeInfo> ss = new ArrayList<>();
            List<TGradeInfo> gradeList = gradeInfoMapper.selectTGradeInfoList(new TGradeInfo()).stream().sorted(Comparator.comparing(TGradeInfo::getSort).reversed()).collect(Collectors.toList());
            for (TGradeInfo g : gradeList) {
                System.out.println(g.getId() + "------------------sort:-------------"+g.getSort());
                ss.add(g);
                ss.add(g);
            }
            System.out.println(ss);
            List<String> supTeamList = ss.stream().filter(bean ->bean.getSort() == 10).map(TGradeInfo::getGradeCode).distinct().collect(Collectors.toList());
            System.out.println(supTeamList);
            UserTeamDto teamMapper = new UserTeamDto();
            teamMapper.setUserId(userId);
            List<UserTeamListVo> teamList = userTeamInfoMapper.selectUserTeamListForParent(teamMapper); //查询本人所在的团队，且会员等级高于本人的上级用户列表
            log.info("-----------------购买终端确认收货，产生办公补贴------------------最高的会员等级id：" + gradeList.get(0).getId());
            for (UserTeamListVo g : teamList) {
                System.out.println(g.getUserId() + "------------------自己的上级用户:-------------");
            }
            teamList.stream().filter(bean ->gradeList.get(0).getId().equals(bean.getGradeId())).collect(Collectors.toList());


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    @RequestMapping(value = "/testWx", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testWx(String APPID, String appSecret) throws IOException {
        try {
            JSONObject jo = weCatUtils.queryWxAccessToken(APPID, appSecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping(value = "/testKuaidiniao", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testKuaidiniao(String appid, String appSecret, String touser, String template_id) throws IOException {
        try {
            // 组装应用级参数
            QueryOrderReq requestData = QueryOrderReq.builder()
                    .customerName("")
                    .orderCode("")
                    .shipperCode("YDKY")
                    .logisticCode("432201263911794")
                    .build();
            String reqURL = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
            String ss = kdApiUtil.buildSystemParams(requestData, "1002", reqURL, "2");
            QueryOrderRes res = JsonUtils.jsonToPojo(ss, QueryOrderRes.class);
            System.out.println("-------22222-----" + res);
            System.out.println("-------22222-----" + ss);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /*public static void main(String[] args) {
        String ss = "{  \"LogisticCode\" : \"432201263911794\",  \"ShipperCode\" : \"YDKY\",  \"Traces\" : [ { \"AcceptTime\": \"2016-10-28 10:44:39\", \"AcceptStation\": \"快件到达【威海】,上一站是【青州分拨中心】\", \"Location\": \"威海市\", \"Action\": \"2\" },{ \"AcceptTime\": \"2016-10-28 10:48:03\", \"AcceptStation\": \"【威海】的【王奕凯】正在派件\", \"Location\": \"威海市\", \"Action\": \"202\" }],  \"State\" : \"0\",  \"EBusinessID\" : \"1726488\",  \"Reason\" : \"暂无轨迹信息\",  \"Success\" : true}";
        QueryOrderRes res = JsonUtils.jsonToPojo(ss, QueryOrderRes.class);
        System.out.println("-------22222-----" + res);
    }*/
    @RequestMapping(value = "/generateOrder", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String generateOrder(String appid, String appSecret, String touser, String template_id) throws IOException {
        try {
            // 组装应用级参数
            GenerateOrderReq.Sender sender = GenerateOrderReq.Sender.builder()
                    .company("LV")
                    .name("Taylor")
                    .mobile("15018442396")
                    .provinceName("上海")
                    .cityName("上海市")
                    .expAreaName("青浦区")
                    .address("明珠路")
                    .build();
            GenerateOrderReq.Receiver receiver = GenerateOrderReq.Receiver.builder()
                    .company("LV")
                    .name("Taylor")
                    .mobile("15018442396")
                    .provinceName("上海")
                    .cityName("上海市")
                    .expAreaName("青浦区")
                    .address("明珠路")
                    .build();
            GenerateOrderReq.Goods goods = GenerateOrderReq.Goods.builder()
                    .goodsName("goodsName")
                    .goodsWeight("1")
                    .goodsquantity("2")
                    .build();
            List<GenerateOrderReq.Goods> commodity = new ArrayList<>();
            commodity.add(goods);
            GenerateOrderReq requestData = GenerateOrderReq.builder()
                    .orderCode("012657018199")
                    .shipperCode("SF")
                    .payType("1")
                    .expType("1")
                    .sender(sender)
                    .receiver(receiver)
                    .commodity(commodity)
                    .weight("1")
                    .quantity("1")
                    .volume("0")
                    .remark("测试萝卜")
                    .build();
            //String requestData = kdApiUtil.orderOnlineByJson(JsonUtils.pojoToJson(bean));
            String reqURL = "https://api.kdniao.com/api/OOrderService";
            //reqURL = "http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json";
            String ss = kdApiUtil.buildSystemParams(requestData, "1801", reqURL, "2");
            GenerateOrderRes res = JsonUtils.jsonToPojo(ss, GenerateOrderRes.class);
            System.out.println("-------22222-----" + res);
            System.out.println("-------22222-----" + ss);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /*public static void main(String[] args) {
        String dd = "{  \"Order\" : {    \"OrderCode\" : \"012657018199\"  },  \"EBusinessID\" : \"1726488\",  \"UniquerRequestNumber\" : \"16baee9d-65b0-4d3e-bfe1-b5cea1922801\",  \"ResultCode\" : \"105\",  \"Reason\" : \"业务暂停开放，如有疑问请联系专属商务经理。\",  \"Success\" : false}";
        GenerateOrderRes res = JsonUtils.jsonToPojo(dd, GenerateOrderRes.class);
        System.out.println("-------22222-----" + res);
    }*/

    @RequestMapping(value = "/testMessageTemplate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testMessageTemplate(String appid, String appSecret, String touser, String template_id) throws IOException {
        try {
            JSONObject first = new JSONObject();
            first.put("value", "终极测试消息模板-再来一下");
            JSONObject delivername = new JSONObject();
            delivername.put("value", "京东物流");
            JSONObject ordername = new JSONObject();
            ordername.put("value", "测试OrderNo");
            JSONObject remark = new JSONObject();
            remark.put("value", "就是不给你发货，你咋的");
            ShipTemplate.Params data = ShipTemplate.Params.builder()
                    .first(first)
                    .delivername(delivername)
                    .ordername(ordername)
                    .remark(remark)
                    .build();
            ShipTemplate template = ShipTemplate.builder()
                    .template_id(template_id)
                    .touser(touser)
                    .url("https://www.baidu.com/")
                    .data(data)
                    .build();
            weCatUtils.sendTemplate(template);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping(value = "/testBody", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testBody() throws IOException {
        try {
            Map<String, String> map = weCatUtils.getPermissionsToSign("baidu");
            System.out.println("------------------" + map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //获取body中的数据
    @RequestMapping(value = "/testRestTemplate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String test() throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("userPhone", "15899874067");
        ResponseEntity<String> temp = restTemplateUtil.post("http://192.168.1.16:8080/api/common/generateVerifyCode", map, String.class);
        if (temp.getStatusCode() == HttpStatus.OK) {
            String ss = temp.getBody();
            return ss;
        } else {
            return "false";
        }
    }
    //获取流中的数据
    @RequestMapping(value = "/testStreamRestTemplate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testStream() throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("userPhone", "15899874067");
        ResponseEntity<Resource> temp = restTemplateUtil.post("http://192.168.1.16:8080/api/common/generateVerifyCode", map, Resource.class);
        if (temp.getStatusCode() == HttpStatus.OK) {
            InputStream ins = temp.getBody().getInputStream();
            return "";
        } else {
            return "false";
        }
    }
}
